<?php
namespace app\api\controller\robat;

use think\Controller;
use app\common\model\user\User;
use app\api\controller\mytool\Mytool;
use app\api\controller\Base;
use app\api\controller\Pub;
use app\common\model\sendmsg\Sendmsg;
use app\common\model\sendmsg\Sendmsglog;
use app\api\controller\mytool\Sendmessage as Sm;
use app\common\model\orderdata\Goods;
use app\common\model\quotation\QuotationList;
use app\common\model\company\Contract;
use app\common\model\cost\Costjournal;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderdelivery\DeliveryList;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\customer\Customer as Customermodel;
use app\common\model\customer\Customervisit;
use app\common\model\apiinput\Apiyunkefriends;
use app\api\controller\mytool\Mapapi;
class Customer extends Base
{
    /**
     * 将没有定位的企业获取定位
     * @return [type] [description]
     */
    public function getlocaltion(){
        $data = Customermodel::whereNull('Lat')->where('Address','not like','%（经纬度可信性')->find();
        if(empty($data['Address'])){$data['Address'] = '';}
        $add = $data['Address'] . $data['Name'];
        $err = false;
        // dump($data);
        if(!empty($add)){
            echo '正在获取'.$add.'请稍等';
            $map = new Mapapi;
            $rdata  = $map->getlocaltion(urlencode($add));
            // dump($rdata);
            if($rdata['status']==0 && $rdata['result']['reliability']>=5){
                $data->Lat = $rdata['result']['location']['lat'];
                $data->Lon = $rdata['result']['location']['lng'];
                $data->Address = $data->Address ."（经纬度可信性".$rdata['result']['reliability']."级）"; 
                $data->save();
                echo "<script>location.reload();</script>";
            }else{
                switch ($rdata['status']) {
                    case '120':
                        echo "每秒已达上限";
                        sleep(1);
                        echo "<script>location.reload();</script>";
                        break;
                    case '121':
                        echo "每日已达上限";
                        break;
                    default:
                        if($rdata['message']=='查询无结果'){
                            $data->Lat = 0;
                            $data->Address = $data['Address'] ."（经纬度可信性较低）【没有找到此定位】"; 
                            echo "<script>location.reload();</script>";
                            $data->save();
                            echo "<script>location.reload();</script>";
                        }elseif($rdata['result']['reliability']<=5){
                            $data->Lat = $rdata['result']['location']['lat'];
                            $data->Lon = $rdata['result']['location']['lng'];
                            $data->Address = $data->Address ."（经纬度可信性".$rdata['result']['reliability']."级）"; 
                            $data->save();
                              echo "<script>location.reload();</script>";
                        }else{
                            echo $rdata['message'];
                        }
                        // $data->RobatMap = -1;
                        // $data->save();
                        // echo "<script>location.reload();</script>";
                        break;
                }
            }
        }else{
            $data->RobatMap = -1;
            $data->save();
            echo "<script>location.reload();</script>";
        }
        
    }

    /**
     * 将没有定位的企业获取定位
     * @return [type] [description]
     */
    public function baidu_tencent_local(){
        echo "暂停使用";
        return ;
        $name = '越华鹏诚数字科技';
        $listdata = Customermodel::where('Name','<>',$name)->limit(10000)->select();
        // $listdata = Customermodel::where('Name',$name)->limit(200)->select();
        if(empty($listdata)||count($listdata)==0){
            // Customermodel::where('Name','操作中：')->update(['Name'=>$name]);
            echo  '转换完成';
            return;
        }
        foreach ($listdata as $key => $data) {
            if(empty($data->Lat)||empty($data->Lon)){
                echo '跳过此条：';
                dump($data);
                echo "\n";
                continue;
            }
            //GPS 转 02
            $sb = Mapapi::wgs84ToGcj02($data->Lat,$data->Lon);
            //坐标09转02
            // $sb = Mapapi::Convert_BD09_To_GCJ02($data->Lat,$data->Lon);

            $data->Lat = $sb['lat'];
            $data->Lon = $sb['lng'];
            // $data->Name = '操作中：'.$name;
            $data->save();
        }
        sleep(3);
        echo "转换中....";
        // echo "<script>location.reload();</script>";
    }

    /**
     * 获取重复的客户信息
     * @return [type] [description]
     */
    public function getdoublelist(){
        $name = Customermodel::group('Name')->having('count(Name) > 1')->column('Name');
        $data = Customermodel::where('Name','in',$name)->order('Name , BussinessId desc,VisitCount asc')
            //->field('Note,BussinessId,CustomerId,Name,VisitCount,CompanyId')
            ->select();
        $ndata = [];
        foreach ($data as $key => $value) {
            if(empty($value['BussinessId'])){
                continue;
            }
            $ndata[$value['Name']][] = $value;
        }
        return myok($ndata);
    }
    /**
     * 去掉重复客户
     * 执行语句 D:\phpstudy_pro\Extensions\php\php7.4.3nts\php.exe index.php api/robat.customer/delete_double_list
     * @return [type] [description]
     */
    public function delete_double_list(){
        $name = Customermodel::group('Name')->having('count(Name) > 1')->column('Name');
        $data = Customermodel::where('Name','in',$name)->order('Name , BussinessId desc,VisitCount asc')->field('BussinessId,LastTime,CustomerId,Name,VisitCount,CompanyId,Tel,UserTel,OtherTel')->select();
        $doublekey = '';//重复的名字
        $delete_array = [];//需要删除的重复数组
        $delete_count = 0;
        $othertel = [];
        //将企业按照名字分组
        foreach ($data as $key => $value) {
            $ndata[$value['Name']][] = $value;
        }
        $i=0;
        foreach ($ndata as $key => $value) {
            echo "正在处理的客户：\n";
            echo "客户名称：".$value[0]['Name']."\n";
            $ids = [];
            $visitcount = 0;
            $LastTime = '';
            $othertel = [];//整合手机信息
            $delete_array = [];
            foreach ($value as $kk => $kv) {
                $delete_array[] = $kv['CustomerId'];
                $visitcount = $visitcount+$kv['VisitCount'];
                $LastTime = $LastTime>$kv['LastTime']?$LastTime:$kv['LastTime'];
                if(!empty($kv['Tel'])){
                    $othertel[] = $kv['Tel'];
                }
                if(!empty($kv['UserTel'])){
                    $othertel[] = $kv['UserTel'];
                }
                if(!empty($kv['OtherTel'])){
                    $othertel = array_merge($kv['OtherTel'],$othertel); 
                }
            }
            if(!empty($othertel)){
                $othertel = array_unique($othertel);
                $othertel = implode(',', $othertel);
            }else{
                $othertel = '';
            }
            unset($delete_array[0]);//去掉第一个客户id
            //调整回访记录表客户id数据 将剩余的回访记录全部转到第一个记录内
                Customervisit::where('CustomerId','in',$delete_array)->update(['CustomerId'=>$value[0]['CustomerId']]);    
                echo "已处理回访记录转移\n";                   
            //调整api表客户id数据
                Apiyunkefriends::where('CustomerId','in',$delete_array)->update(['CustomerId'=>$value[0]['CustomerId']]);
            //调整客户回访次数
                echo "VisitCount：".$visitcount."\n";
                echo "LastTime：".$LastTime."\n";
                echo "OtherTel：".$othertel."\n";
                Customermodel::where('CustomerId',$value[0]['CustomerId'])->update(['VisitCount'=>$visitcount,'LastTime'=>$LastTime,'OtherTel'=>$othertel]);
                Customermodel::where('CustomerId','in',$delete_array)->delete();//删掉这些客户
            echo "已处理第".$i++."个，共".count($ndata)."个完成\n\n";
        }
        return myok('已清理'.count($ndata).'个客户的重复信息');
    }
    // public function test(){
    //     dump(Mapapi::wgs84ToGcj02(38.26137551,116.86864827));
    // }
}
